﻿using MeetingRoomBooking.Application.Common.Interfaces;
using MeetingRoomBooking.Domain.Entities;
using MeetingRoomBooking.Domain.Events;

namespace MeetingRoomBooking.Application.Bookings.Commands;
public class UpdateBookingCommand : IRequest
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int RoomId { get; set; }
    public int UserId { get; set; }
    public required string Title { get; set; }
    public string? Description { get; set; }
    public int Id { get; set; }
}

public class UpdateBookingCommandValidator : AbstractValidator<UpdateBookingCommand>
{
    public UpdateBookingCommandValidator()
    {
        RuleFor(x => x.Id).NotEmpty().WithMessage("Id is required.");

        RuleFor(x => x.Title).NotEmpty().WithMessage("Title is required.");

        RuleFor(x => x.RoomId).NotNull().GreaterThan(0).WithMessage("Room Id must be a valid positive number.");

        RuleFor(x => x.StartDate)
             .NotEqual(DateTime.MinValue).WithMessage("Start date is required.")
             .GreaterThan(DateTime.Now.Date).WithMessage("Start date must be greater than now.");

        RuleFor(x => x.EndDate)
            .NotEqual(DateTime.MinValue).WithMessage("End date is required.")
            .GreaterThan(x => x.StartDate).WithMessage("End date must be greater than start date.");
    }
}
public class UpdateBookingCommandCommandHandler : IRequestHandler<UpdateBookingCommand>
{
    private readonly IApplicationDbContext _context;
    private readonly IUser _user;

    public UpdateBookingCommandCommandHandler(IApplicationDbContext context, IUser user)
    {
        _context = context;
        _user = user;
    }

    public async Task Handle(UpdateBookingCommand request, CancellationToken cancellationToken)
    {
        var booking =await _context.Bookings.FindAsync(request.Id);

        if(booking == null) throw  new Exception($"Booking Id:{request.Id} not found.");

        booking.StartDate=request.StartDate;
        booking.EndDate=request.EndDate;
        booking.Description=request.Description;
        booking.Created=DateTime.Now;
        booking.RoomId=request.RoomId;
        booking.LastModified=DateTime.Now;
        booking.LastModifiedBy = _user.Id;

        await _context.SaveChangesAsync(cancellationToken);
    }
}
